const express = require('express');
const router = express.Router();
const fs = require("fs");
const mongo = require('../dataBase/db');
const multer = require('multer');

var upload = multer({ dest: './static/image' }).any();
router.post('/', upload, function(req, res) {
    console.log(req.files[0]);
    var oldName = req.files[0].filename;
    var newName = req.files[0].fieldname;
    var type = req.files[0].mimetype;
    type = type.slice(6, type.length);
    var src = "./static/image/" + oldName;
    let newPath = './static/image/' + newName + '.' + type;
    fs.rename(src, newPath, function(err) {
        if (err) throw err;
        if (!err) {
            console.log(newPath + ' replace success');
            let userId = newName;
            mongo.users.update({ userId: userId }, { avatarImg: `image/${userId}.${type}` }, (err, row) => {
                if (err) res.send({ status: false });
                console.log(row);
                res.send({ status: true });
            })
        }
    })
})
router.post('/changeAvatar', upload, function(req, res) {
    var oldName = req.files[0].filename;
    var newName = req.files[0].fieldname;
    var type = req.files[0].mimetype;
    type = type.slice(6, type.length);
    var src = "./static/image/" + oldName;
    let newPath = './static/image/' + newName + '.' + type;
    fs.rename(src, newPath, function(err) {
        if (err) throw err;
        if (!err) {
            console.log(`userID:${newName} 成功替换了头像!`);
            res.send({ status: true });
        }
    })
})
module.exports = router;